package com.example.huanhang.changzhouapp.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.huanhang.changzhouapp.MainActivity;
import com.example.huanhang.changzhouapp.R;
import com.example.huanhang.changzhouapp.base.BaseActivity;
import com.example.huanhang.changzhouapp.bean.User;
import com.example.huanhang.changzhouapp.util.NetWorkUtil;
import com.example.huanhang.changzhouapp.util.ThreadUtil;
import com.example.huanhang.changzhouapp.util.ToastUtil;
import com.github.glomadrian.grav.GravView;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import static com.example.huanhang.changzhouapp.R.id.et_password;
import static com.example.huanhang.changzhouapp.R.id.et_username;
import static com.example.huanhang.changzhouapp.util.ConstantUtils.IS_WRITE_OFF;

/**
 * @author lei
 * @desc 登录界面
 * @date 2018/8/25 0025 -- 下午 6:07.
 * 个人博客站: http://www.bestlei.top
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText mEtUsername;
    private EditText mEtPassword;
    private Button mLoginBtn;
    private CardView mCardview;
    private GravView mGrav;
    private User mUser;
    private List<User> mList = new ArrayList<>();
    private SharedPreferences loginSp;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        mEtUsername = (EditText) findViewById(et_username);
        mEtPassword = (EditText) findViewById(et_password);
        mLoginBtn = (Button) findViewById(R.id.login_btn);
        mCardview = (CardView) findViewById(R.id.cardview);
        mGrav = (GravView) findViewById(R.id.grav);
        mLoginBtn.setOnClickListener(this);
        ImmersionBar.with(this).init();
    }

    @Override
    public void initData() {
        if (!NetWorkUtil.isNetworkConnected(this)) {
            ToastUtil.longToast(this, "网络未连接!");
        }
        loginSp = getSharedPreferences("login", MODE_PRIVATE);
        //判断是否为注销跳转
        if (getIntent().getStringExtra(IS_WRITE_OFF) != null) {
            mEtUsername.setText("");
            mEtPassword.setText("");
            //解决注销后未登录退出可继续登录的问题
            loginSp.edit().putString("userName", "").apply();
            loginSp.edit().putString("passWord", "").apply();
        } else {
            String userName = loginSp.getString("userName", "");
            String passWord = loginSp.getString("passWord", "");
            if (!TextUtils.isEmpty(userName) || !TextUtils.isEmpty(passWord)) {
                mEtUsername.setText(userName);
                mEtPassword.setText(passWord);
                initLogin(userName, passWord);
            }
        }
    }

    private void initLogin(String username, String password) {
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM t_sys_person WHERE lccb_name='" + username + "' and lccb_pwd='" + password + "'";
            try {
                ResultSet result = ThreadUtil.result(sql);
                if (result.next()) {
                    mUser = new User();
                    mUser.setName(result.getString("lccb_name"));
                    mUser.setPwd(result.getString("lccb_pwd"));
                    mUser.setBm(result.getString("lccb_bm"));
                    mUser.setGzName(result.getString("lccb_gzname"));
                    mUser.setState(result.getString("lccb_state"));
                    mUser.setXb(result.getString("lccb_xb"));
                    mUser.setId(result.getString("id"));
                    mUser.setPermissions(result.getString("lccb_permissions"));
                    mList.add(mUser);
                    EventBus.getDefault().postSticky(mUser);
                }

                querySuccess();
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void querySuccess() {
        ThreadUtil.runOnUiThread(() -> {
            if (mList.size() != 0) {
                dismissWaitDialog();
                mCardview.setVisibility(View.VISIBLE);
                loginSp.edit().putString("userName", mUser.getName()).apply();
                loginSp.edit().putString("passWord", mUser.getPwd()).apply();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            } else {
                dismissWaitDialog();
                mCardview.setVisibility(View.VISIBLE);
                ToastUtil.toast(LoginActivity.this, "请检查用户名密码是否正确");
            }

        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn:
                submit();
                break;
        }
    }

    private void submit() {
        showWaitDialog("登录中...");
        mCardview.setVisibility(View.GONE);
        // validate
        String username = mEtUsername.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = mEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        initLogin(username, password);
    }
}
